<?php

require_once("classes/security.class.php");
require_once("classes/db_functions.php");
require_once("classes/functions.php");

$sec = new security();
$logged = $sec->isUserLoggedIn();
$action = getFromInput("a");

if(!$logged) {
	die("<h1>Authorisation required.</h1>");
}
showstartform();
switch ($action){
	case "login":
		$sec->userLogin(getFromInput("username"),getFromInput("password"));
		break;
	case "update":
		updaterokovnik();
		break;
}

function showstartform(){
	$sa = getFromInput("sa");
	$na = getFromInput("na");
	echo '
	<style>
	form{
		font-family:Arial;
		font-size:12px;
	}
	label{
		display:block;
		float:left;
		padding-top:7px;
		clear:both;
	}
	input{
		float:left;
		margin:5px;
	}
	input[type=text]{
		width:60px;
	}
	input[type=submit]{
		clear:both;
	}
	</style>
	<form method="POST" action="javascript:void(0)" onsubmit="if(confirm(\'potvrdite:\\n\\n\'+this.sa.value+\'=>\'+this.na.value+\'\\n\')){this.action=\''.$_SERVER['PHP_SELF'].'\'; this.submit();}">
		<h2>Prebacivanje poziva rokovnika sa komitenta na komitenta</h2>
		<input type="hidden" name="a" value="update" />
		<label for="sa">SA:</label> <input type="text" name="sa" id="sa" value="'.$sa.'" /><br />
		<label for="na">NA:</label> <input type="text" name="na" id="na" value="'.$na.'" />
		<input type="submit" value="izmeni" />
	</form>
	<script>var obj = document.getElementById(\'sa\'); obj.focus(); obj.select();</script>
	';
}
function updaterokovnik(){
	$db = new db_functions();
	$sa = getFromInput("sa");
	$na = getFromInput("na");
	
	echo '<hr style="clear:both" />';
	
	$q = "SELECT id FROM rokovnik WHERE komitent_id='$sa'";
	$res = $db->select1($q);
	if($res){
		$num = count($res);
		$ids = array();
		foreach ($res as $row){
			$ids[count($ids)] = $row[0];
		}
		if($db->alterTable("UPDATE rokovnik SET komitent_id=$na WHERE komitent_id=$sa")){
			$affected = affectedRows($db);
			echo "<strong>$affected</strong> rows affected.<br />ROKOVNIK IDS: ".implode(", ",$ids);
			file_put_contents("logs/rokovnik/sana.log",date("d.m.Y H:i")."\t$sa\t$na\t".implode(",",$ids)."\r\n",FILE_APPEND);
		}else{
			die(mysql_error());
		}
		
		//$db->numRows();
	}else{
		echo "Nema zabeleženih poziva u rokovniku za komitenta: <strong>$sa</strong>";
	}
	
	
}

function affectedRows($db){
	$num = $db->_site_config->_database->num_rows;
	if (is_array($num)) {
		return array_pop($num);
	}else{
		return $num;
	}
}
?>